package com.edou.cms.controller.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.edou.cms.form.CmsBlogAuthorForm;
import com.edou.cms.dto.CmsTagCondition;
import com.edou.cms.entity.CmsBlogArticle;
import com.edou.cms.entity.CmsBlogAuthor;
import com.edou.cms.entity.CmsBlogAuthorTag;
import com.edou.cms.entity.CmsTag;
import com.edou.cms.service.ICmsBlogArticleService;
import com.edou.cms.service.ICmsBlogAuthorService;
import com.edou.cms.service.ICmsBlogAuthorTagService;
import com.edou.cms.service.ICmsTagService;
import com.edou.base.token.TokenValidate;
import com.edou.base.controller.BaseController;


@Controller("cmsBlogAuthorController")
@Scope("prototype")
@RequestMapping("/admin/cms/blog/author")
public class CmsBlogAuthorController extends BaseController {

	@Resource(name = "cmsBlogAuthorServiceImpl")
	private ICmsBlogAuthorService cmsBlogAuthorService;

	@Resource(name = "cmsTagServiceImpl")
	private ICmsTagService cmsTagService;
	
	@Resource(name = "cmsBlogAuthorTagServiceImpl")
	private ICmsBlogAuthorTagService cmsBlogAuthorTagService;
	
	@Resource(name = "cmsBlogArticleServiceImpl")
	private ICmsBlogArticleService cmsBlogArticleService;

	/**
	 * 首页
	 * @return 
	 */
	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public ModelAndView index(CmsBlogAuthorForm model,HttpServletRequest request,HttpServletResponse respose){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/cms/cms_blog_author_index");
		Map<String, Object> data = view.getModel();
		
		Integer type = model.getType();
		data.put("type", type);
		
		return view;
	}

	
	/**
	 * 分页查询
	 * @return 
	 */
	@RequestMapping(value = "/listCmsBlogAuthorByPage.htm", method = RequestMethod.POST)
	public void listCmsBlogAuthorByPage(@ModelAttribute CmsBlogAuthorForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try{
			cmsBlogAuthorService.listCmsBlogAuthorByPage(model.getPageResult(),model.getCondition());
			List<CmsBlogAuthor> cmsBlogAuthorList = model.getPageResult().getResult();
			List<CmsBlogArticle> cmsBlogArticleList = new ArrayList<CmsBlogArticle>();
			for (CmsBlogAuthor cmsBlogAuthor : cmsBlogAuthorList) {
				cmsBlogArticleList = cmsBlogArticleService.listCmsBlogArticleByAuthorId(cmsBlogAuthor.getId());
				cmsBlogAuthor.setNumArticle(cmsBlogArticleList.size());
			}
			JSONObject root = toPageJson(model.getPageResult(), new String[]{"id","name","nameSub","descBrief","descHtml","sort","numArticle","countCollect","countView","countLike","isBest","isRecommend","isNew"});
			ajaxPageResult(root,response);
		}catch(Exception ex){
			String msg = "查询博客博主时发生异常："+ex.getMessage();
			logger.error(msg,ex);
		}
	}

	/**
	 * 保存博客博主-跳转到添加页面
	 * @return 
	 */
	@RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
	public ModelAndView edit(@ModelAttribute CmsBlogAuthorForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/cms/cms_blog_author_add");
		Map<String,Object> data = view.getModel();
		StringBuffer strs = new StringBuffer();
		String str = "";
		if(StringUtils.isNotBlank(model.getItem().getId())){
			// 根据自媒体（博主）id获取一个对象
			CmsBlogAuthor item = cmsBlogAuthorService.getCmsBlogAuthorById(model.getItem().getId());
			// 根据自媒体（博主）id获取cms_blog_author_tag表中的集合
			List<CmsBlogAuthorTag> cmsBlogAuthorTagList = cmsBlogAuthorTagService.listCmsBlogAuthorTagByAuthorId(model.getItem().getId());
			// 进行遍历  获取每个对象的tagid
			for (CmsBlogAuthorTag cmsBlogAuthorTag : cmsBlogAuthorTagList) {
				CmsTag cmsTag = cmsTagService.getCmsTagById(cmsBlogAuthorTag.getTagId());
				str = strs.append(cmsTag.getId()).toString();
			}
			item.setTagList(str);
			
			data.put("item", item);
			
		}
		Integer type = model.getType();
		data.put("type", type);
		
		// 查询类别为自媒体的标签
		CmsTagCondition condition = new CmsTagCondition();
		condition.setType(1);
		List<CmsTag> cmsTagList = cmsTagService.listCmsTagByType(condition);
		data.put("cmsTagList", cmsTagList);
		
		return view;
	}
	
	/**
	 * 保存博客博主
	 * @return 
	 */
	@RequestMapping(value = "/saveCmsBlogAuthor.htm", method = RequestMethod.POST)
	@TokenValidate
	public ModelAndView saveRole(@ModelAttribute CmsBlogAuthorForm model,HttpServletRequest request,HttpSession session){
		try {
			if(StringUtils.isBlank(model.getItem().getId())){
				Integer type = model.getItem().getType();
				// 当类型是博主
				if(type==1){
					model.getItem().setType(1);
				}
				// 当类型是自媒体
				if(type==2){
					model.getItem().setType(2);
				}
				cmsBlogAuthorService.add(model.getItem());
			}else{
				CmsBlogAuthor item = cmsBlogAuthorService.getCmsBlogAuthorById(model.getItem().getId());
				item.setName(model.getItem().getName());
				item.setNameSub(model.getItem().getNameSub());
				item.setDescBrief(model.getItem().getDescBrief());
				item.setDescHtml(model.getItem().getDescHtml());
				item.setPhotoUrl(model.getItem().getPhotoUrl());
				item.setCodeImg(model.getItem().getCodeImg());
				item.setSort(model.getItem().getSort());
				item.setIsRecommend(model.getItem().getIsRecommend());
				item.setTagList(model.getItem().getTagList());
				cmsBlogAuthorService.update(item);
			}
			return ajaxJSON(Status.success,"保存成功");
		} catch (Exception e) {
			String msg = "保存博客博主时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "保存失败，请稍后重试");
		}
	}
	
	/**
	 * 删除CmsBlogAuthor
	 * @return 
	 */
	@RequestMapping(value = "/del.htm", method = RequestMethod.POST)
	public ModelAndView del(@ModelAttribute CmsBlogAuthorForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			cmsBlogAuthorService.delByIds(model.getSelIds().split(","));
			return ajaxJSON(Status.success,"删除成功");
		} catch (Exception e) {
			String msg = "删除时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "删除失败，请稍后重试");
		}
	}



}

